package com.example.campuslink.commen.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import java.util.Stack

class DrawingBoardView : View {
    private var drawPath: Path? = null
    private var drawPaint: Paint? = null
    private var canvasPaint: Paint? = null
    private var paintColor = Color.BLACK
    private var drawCanvas: Canvas? = null
    private var process = 20
    var drawingBitmap: Bitmap? = null
        private set
    private var pathStack: Stack<Path?>? = null
    private var redoStack: Stack<Path?>? = null
    private var colorStack: Stack<Int>? = null
    private var redocolor: Stack<Int>? = null
    private var procsstack: Stack<Int>? = null
    private var redoprocess: Stack<Int>? = null

    constructor(context: Context?) : super(context) {
        setupDrawing()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        setupDrawing()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        setupDrawing()
    }

    private fun setupDrawing() {
        pathStack = Stack()
        redoStack = Stack()
        colorStack = Stack()
        redocolor = Stack()
        procsstack = Stack()
        redoprocess = Stack()
        // 初始化画笔
        drawPaint = Paint()
        drawPaint!!.color = paintColor
        drawPaint!!.isAntiAlias = true
        drawPaint!!.strokeWidth = 5f
        drawPaint!!.style = Paint.Style.STROKE
        drawPaint!!.strokeJoin = Paint.Join.ROUND
        drawPaint!!.strokeCap = Paint.Cap.ROUND

        // 用于绘制的画布的画笔（颜色透明，只显示绘制的线条等内容）
        canvasPaint = Paint(Paint.DITHER_FLAG)

        // 触摸路径，用于记录手指移动轨迹
        drawPath = Path()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        // 创建一个与View大小相同的Bitmap作为画布
        drawingBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        drawCanvas = Canvas(drawingBitmap!!)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // 将缓存的Bitmap绘制到View的Canvas上，显示之前绘制的内容
        canvas.drawBitmap(drawingBitmap!!, 0f, 0f, canvasPaint)
        // 在当前Canvas上绘制路径（也就是正在绘制的线条）
        canvas.drawPath(drawPath!!, drawPaint!!)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val touchX = event.x
        val touchY = event.y
        when (event.action) {
            MotionEvent.ACTION_DOWN -> drawPath!!.moveTo(touchX, touchY)
            MotionEvent.ACTION_MOVE -> drawPath!!.lineTo(touchX, touchY)
            MotionEvent.ACTION_UP -> {
                drawCanvas!!.drawPath(drawPath!!, drawPaint!!)
                pathStack!!.push(drawPath) // 将路径添加到栈中
                colorStack!!.push(paintColor)
                procsstack!!.push(process)
                drawPath = Path()
            }

            else -> return false
        }
        invalidate()
        return true
    }

    fun setPaintThickness(project: Int) {
        process = project
        procsstack!!.add(project)
        drawPaint!!.strokeWidth = project.toFloat()
        invalidate()
    }

    private var isEraserEnabled = false

    fun enableEraser(enabled: Boolean, previousStrokeWidth: Int) {
        isEraserEnabled = enabled
        if (isEraserEnabled) {
            drawPaint!!.color = Color.WHITE
            drawPaint!!.strokeWidth = previousStrokeWidth.toFloat()
        } else {
            drawPaint!!.color = paintColor
            drawPaint!!.strokeWidth = previousStrokeWidth.toFloat()
        }
        invalidate()
    }

    fun setPaintColor(color: Int) {
        paintColor = color
        drawPaint!!.color = color
        invalidate()
    }

    // 新增的清除画布方法
    fun clearCanvas(previousStrokeWidth: Int) {
        if (drawCanvas != null && drawingBitmap != null) {
            // 创建一个新的空白Bitmap，覆盖原来的画布Bitmap
            drawingBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            drawCanvas = Canvas(drawingBitmap!!)
            // 可以选择将画笔等相关设置重置为初始状态，比如颜色、粗细等
            drawPaint!!.color = Color.BLACK
            drawPaint!!.strokeWidth = previousStrokeWidth.toFloat()
            colorStack!!.clear()
            redoprocess!!.clear()
            redocolor!!.clear()
            redoStack!!.clear()
            pathStack!!.clear()
            procsstack!!.clear()
            // 触发重绘，使界面显示空白画布
            invalidate()
        }
    }

    //撤销
    fun undoLastStep() {
        if (!pathStack!!.isEmpty()) {
            val undonePath = pathStack!!.pop()
            redoStack!!.push(undonePath) // 将被撤销的路径添加到恢复栈
            val tempcolor = colorStack!!.pop()
            redocolor!!.push(tempcolor)
            val tempproject = procsstack!!.pop()
            redoprocess!!.push(tempproject)
            // 重新创建一个空白画布
            drawingBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            drawCanvas = Canvas(drawingBitmap!!)
            // 重新绘制所有剩余的路径
            for (i in pathStack!!.indices) {
                val path = pathStack!![i]
                val c = colorStack!![i]
                drawPaint!!.color = c
                drawPaint!!.strokeWidth = tempproject.toFloat()
                drawCanvas!!.drawPath(path!!, drawPaint!!)
            }
            //            for (Path path : pathStack) {
//                drawCanvas.drawPath(path, drawPaint);
//            }
            invalidate()
            drawPaint!!.color = paintColor
            drawPaint!!.strokeWidth = process.toFloat()
            invalidate()
        }
    }

    fun redoLastStep() {
        if (!redoStack!!.isEmpty()) {
            val redonePath = redoStack!!.pop()
            val tempcolor = redocolor!!.pop()
            val tempro = redoprocess!!.pop()
            pathStack!!.push(redonePath)
            colorStack!!.push(tempcolor)
            procsstack!!.push(tempro)
            drawPaint!!.color = tempcolor
            drawPaint!!.strokeWidth = tempro.toFloat()
            drawCanvas!!.drawPath(redonePath!!, drawPaint!!)
            invalidate()
            drawPaint!!.color = paintColor
            drawPaint!!.strokeWidth = process.toFloat()
            invalidate()
        }
    }
}